<?php
/**
 * 错误报告和优化建议系统
 * Error Reporting and Optimization Suggestions System
 * 
 * @package WP Bootstrap Woo
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * 错误报告生成器类
 */
class WBW_Report_Generator {
    
    private $report_data = array();
    private $suggestions = array();
    
    public function __construct() {
        // 初始化
    }
    
    /**
     * 生成完整报告
     */
    public function generate_complete_report($syntax_results, $performance_results) {
        $this->report_data = array(
            'timestamp' => current_time('timestamp'),
            'syntax_check' => $syntax_results,
            'performance_check' => $performance_results,
            'summary' => $this->generate_summary($syntax_results, $performance_results),
            'recommendations' => $this->generate_recommendations($syntax_results, $performance_results)
        );
        
        return $this->report_data;
    }
    
    /**
     * 生成摘要
     */
    private function generate_summary($syntax_results, $performance_results) {
        $total_issues = 0;
        $critical_issues = 0;
        
        if (isset($syntax_results['errors'])) {
            $total_issues += count($syntax_results['errors']);
            $critical_issues += count($syntax_results['errors']);
        }
        
        if (isset($syntax_results['warnings'])) {
            $total_issues += count($syntax_results['warnings']);
        }
        
        $performance_score = $performance_results['performance_score'] ?? 0;
        
        return array(
            'total_issues' => $total_issues,
            'critical_issues' => $critical_issues,
            'performance_score' => $performance_score,
            'status' => $this->determine_overall_status($critical_issues, $performance_score)
        );
    }
    
    /**
     * 确定整体状态
     */
    private function determine_overall_status($critical_issues, $performance_score) {
        if ($critical_issues > 0) {
            return 'critical';
        } elseif ($performance_score < 60) {
            return 'warning';
        } else {
            return 'good';
        }
    }
    
    /**
     * 生成建议
     */
    private function generate_recommendations($syntax_results, $performance_results) {
        $recommendations = array();
        
        // 语法修复建议
        if (isset($syntax_results['errors']) && !empty($syntax_results['errors'])) {
            $recommendations[] = array(
                'type' => 'syntax_fix',
                'priority' => 'high',
                'title' => '修复语法错误',
                'description' => '检测到语法错误，需要立即修复',
                'actions' => array('使用自动修复功能', '手动检查代码语法', '备份文件后进行修复')
            );
        }
        
        // 性能优化建议
        if (isset($performance_results['optimization_suggestions'])) {
            $recommendations = array_merge($recommendations, $performance_results['optimization_suggestions']);
        }
        
        return $recommendations;
    }
    
    /**
     * 生成HTML报告
     */
    public function generate_html_report() {
        if (empty($this->report_data)) {
            return '<div class="notice notice-error"><p>没有可用的报告数据</p></div>';
        }
        
        $html = '<div class="wbw-report-container">';
        
        // 摘要部分
        $html .= $this->render_summary_section();
        
        // 语法检查结果
        $html .= $this->render_syntax_results();
        
        // 性能检查结果
        $html .= $this->render_performance_results();
        
        // 建议部分
        $html .= $this->render_recommendations();
        
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * 渲染摘要部分
     */
    private function render_summary_section() {
        $summary = $this->report_data['summary'];
        $status_class = 'notice-' . ($summary['status'] === 'critical' ? 'error' : ($summary['status'] === 'warning' ? 'warning' : 'success'));
        
        $html = '<div class="summary-section ' . $status_class . '">';
        $html .= '<h3>检查摘要</h3>';
        $html .= '<p>总问题数: ' . $summary['total_issues'] . '</p>';
        $html .= '<p>严重问题: ' . $summary['critical_issues'] . '</p>';
        $html .= '<p>性能评分: ' . $summary['performance_score'] . '/100</p>';
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * 渲染语法结果
     */
    private function render_syntax_results() {
        $results = $this->report_data['syntax_check']['results'] ?? array();
        
        $html = '<div class="syntax-results-section">';
        $html .= '<h3>语法检查结果</h3>';
        
        foreach ($results as $result) {
            if ($result['type'] === 'section') {
                $html .= '<h4>' . esc_html($result['title']) . '</h4>';
            } else {
                $icon = $this->get_status_icon($result['type']);
                $html .= '<p>' . $icon . ' ' . esc_html($result['message']) . '</p>';
            }
        }
        
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * 渲染性能结果
     */
    private function render_performance_results() {
        $results = $this->report_data['performance_check']['results'] ?? array();
        
        $html = '<div class="performance-results-section">';
        $html .= '<h3>性能检查结果</h3>';
        
        foreach ($results as $result) {
            if ($result['type'] === 'section') {
                $html .= '<h4>' . esc_html($result['title']) . '</h4>';
            } else {
                $icon = $this->get_status_icon($result['type']);
                $html .= '<p>' . $icon . ' ' . esc_html($result['message']) . '</p>';
            }
        }
        
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * 渲染建议
     */
    private function render_recommendations() {
        $recommendations = $this->report_data['recommendations'] ?? array();
        
        if (empty($recommendations)) {
            return '<div class="notice notice-success"><p>✅ 没有发现需要改进的问题</p></div>';
        }
        
        $html = '<div class="recommendations-section">';
        $html .= '<h3>优化建议</h3>';
        
        foreach ($recommendations as $rec) {
            $priority_class = 'priority-' . ($rec['priority'] ?? 'medium');
            $html .= '<div class="recommendation-item ' . $priority_class . '">';
            $html .= '<h4>' . esc_html($rec['title']) . '</h4>';
            $html .= '<p>' . esc_html($rec['description']) . '</p>';
            
            if (isset($rec['actions']) && is_array($rec['actions'])) {
                $html .= '<ul>';
                foreach ($rec['actions'] as $action) {
                    $html .= '<li>' . esc_html($action) . '</li>';
                }
                $html .= '</ul>';
            }
            
            $html .= '</div>';
        }
        
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * 获取状态图标
     */
    private function get_status_icon($type) {
        switch ($type) {
            case 'success':
                return '✅';
            case 'error':
                return '❌';
            case 'warning':
                return '⚠️';
            case 'info':
                return 'ℹ️';
            default:
                return '•';
        }
    }
    
    /**
     * 导出报告为JSON
     */
    public function export_json() {
        return json_encode($this->report_data, JSON_PRETTY_PRINT);
    }
    
    /**
     * 保存报告到文件
     */
    public function save_report($format = 'json') {
        $upload_dir = wp_upload_dir();
        $reports_dir = $upload_dir['basedir'] . '/syntax-reports';
        
        if (!file_exists($reports_dir)) {
            wp_mkdir_p($reports_dir);
        }
        
        $filename = 'syntax-report-' . date('Y-m-d-H-i-s') . '.' . $format;
        $file_path = $reports_dir . '/' . $filename;
        
        if ($format === 'json') {
            $content = $this->export_json();
        } else {
            $content = $this->generate_html_report();
        }
        
        if (file_put_contents($file_path, $content)) {
            return $file_path;
        }
        
        return false;
    }
}